package com.ticket.sass.provider.util;

import com.google.gson.*;

import java.lang.reflect.Type;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Objects;

public class GsonUtil {
    private static final Gson gson = buildGson();
    
    private GsonUtil() {
        // 私有构造函数，防止实例化
    }
    
    public static Gson getInstance() {
        return gson;
    }
    
    private static Gson buildGson() {
        return new GsonBuilder()
            .registerTypeAdapter(LocalDateTime.class, new LocalDateTimeAdapter())
            .registerTypeAdapter(LocalDate.class, new LocalDateAdapter())
            .setDateFormat("yyyy-MM-dd'T'HH:mm:ss") // 设置日期格式
            .create();
    }
    
    private static class LocalDateTimeAdapter implements JsonSerializer<LocalDateTime>,
        JsonDeserializer<LocalDateTime> {
        
        private final DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss");
        
        @Override
        public JsonPrimitive serialize(LocalDateTime src, Type typeOfSrc, JsonSerializationContext context) {
            return new JsonPrimitive(formatter.format(src));
        }
        
        @Override
        public LocalDateTime deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) {
            return LocalDateTime.parse(json.getAsString(), formatter);
        }
    }
    
    private static class LocalDateAdapter implements JsonSerializer<LocalDate>,
        JsonDeserializer<LocalDate> {
        
        private final DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        
        @Override
        public JsonPrimitive serialize(LocalDate src, Type typeOfSrc, JsonSerializationContext context) {
            return new JsonPrimitive(formatter.format(src));
        }
        
        @Override
        public LocalDate deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) {
            return LocalDate.parse(json.getAsString(), formatter);
        }
    }
    
    public static String toJsonString(Object obj){
        if (Objects.isNull(obj)){
            return "{}";
        }
        
        return gson.toJson(obj);
    }
}
